package com.example.xiaoshuo_yudu.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.xiaoshuo_yudu.entity.Result;
import com.example.xiaoshuo_yudu.entity.dto.NewsUpdateDTO;
import com.example.xiaoshuo_yudu.entity.entity.News;
import com.example.xiaoshuo_yudu.service.impl.NewsServiceImpl;
import com.example.xiaoshuo_yudu.utils.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员新闻管理控制器
 */
@RestController

@RequestMapping("/api/admin/news")
public class AdminNewsController {

    @Autowired
    private NewsServiceImpl newsService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private static final String NEWS_KEY = Const.NEWS_SELECT;

    /**
     * 分页查询新闻列表
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param keyword 搜索关键词
     * @return 新闻列表
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> listNews(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword) {
        
        // 使用MyBatis Plus的分页功能
        Page<News> page = new Page<>(pageNum, pageSize);
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.like("news_title", keyword)
                    .or()
                    .like("publisher", keyword);
        }
        queryWrapper.orderByAsc("id");
        
        Page<News> resultPage = newsService.page(page, queryWrapper);
        List<News> newsList = resultPage.getRecords();
        long total = resultPage.getTotal();
        
        Map<String, Object> data = new HashMap<>();
        data.put("list", newsList);
        data.put("total", total);
        
        return Result.success(data);
    }

    /**
     * 添加新闻
     * @param newsUpdateDTO 新闻信息
     * @return 添加结果
     */
    @PostMapping("/add")
    public Result<Void> addNews(@RequestBody NewsUpdateDTO newsUpdateDTO) {
        News news = new News();
        // 手动映射字段，因为DTO和实体类字段名不一致
        news.setNewsTitle(newsUpdateDTO.getTitle());
        news.setNewsContent(newsUpdateDTO.getContent());
        news.setPublisher(newsUpdateDTO.getAuthor());
        // News实体类中没有status和publishTime字段，需要根据实际情况处理
        
        if (newsService.save(news)) {
            redisTemplate.delete(NEWS_KEY);
            return Result.success();
        } else {
            return Result.failure(500, "添加新闻失败");
        }
    }

    /**
     * 更新新闻信息
     * @param newsUpdateDTO 新闻信息
     * @return 更新结果
     */
    @PutMapping("/update")
    public Result<Void> updateNews(@RequestBody NewsUpdateDTO newsUpdateDTO) {
        if (newsUpdateDTO.getNewsId() == null) {
            return Result.failure(400, "新闻ID不能为空");
        }
        
        News news = newsService.getById(newsUpdateDTO.getNewsId());
        if (news == null) {
            return Result.failure(404, "新闻不存在");
        }
        
        // 手动映射字段
        news.setNewsTitle(newsUpdateDTO.getTitle());
        news.setNewsContent(newsUpdateDTO.getContent());
        news.setPublisher(newsUpdateDTO.getAuthor());
        // News实体类中没有status和publishTime字段，需要根据实际情况处理
        
        if (newsService.updateById(news)) {
            redisTemplate.delete(NEWS_KEY);
            return Result.success();
        } else {
            return Result.failure(500, "更新新闻失败");
        }
    }

    /**
     * 删除新闻
     * @param newsId 新闻ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{newsId}")
    public Result<Void> deleteNews(@PathVariable Integer newsId) {
        if (newsService.removeById(newsId)) {
            redisTemplate.delete(NEWS_KEY);
            return Result.success();
        } else {
            return Result.failure(500, "删除新闻失败");
        }
    }

    /**
     * 批量删除新闻
     * @param newsIds 新闻ID列表
     * @return 删除结果
     */
    @DeleteMapping("/batch-delete")
    public Result<Void> batchDeleteNews(@RequestBody List<Integer> newsIds) {
        if (newsService.removeBatchByIds(newsIds)) {
            redisTemplate.delete(NEWS_KEY);
            return Result.success();
        } else {
            return Result.failure(500, "批量删除新闻失败");
        }
    }

    /**
     * 根据ID获取新闻详情
     * @param newsId 新闻ID
     * @return 新闻详情
     */
    @GetMapping("/detail/{newsId}")
    public Result<News> getNewsDetail(@PathVariable Integer newsId) {
        News news = newsService.getById(newsId);
        if (news != null) {
            redisTemplate.delete(NEWS_KEY);
            return Result.success(news);
        } else {
            return Result.failure(404, "新闻不存在");
        }
    }

    /**
     * 发布新闻
     * @param newsId 新闻ID
     * @return 发布结果
     */
    @PutMapping("/publish/{newsId}")
    public Result<Void> publishNews(@PathVariable Integer newsId) {
        News news = newsService.getById(newsId);
        if (news == null) {
            return Result.failure(404, "新闻不存在");
        }
        if (newsService.updateById(news)) {
            redisTemplate.delete(NEWS_KEY);
            return Result.success();
        } else {
            return Result.failure(500, "发布新闻失败");
        }
    }
}